package us.sunrisemorning.pixivbrower.web.pulgin;

import com.jfinal.plugin.IPlugin;
import com.jfinal.plugin.activerecord.IDataSourceProvider;
import org.flywaydb.core.Flyway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FlywayPlugin implements IPlugin {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private IDataSourceProvider dataSourceProvider;

    public FlywayPlugin(IDataSourceProvider dataSourceProvider) {
        this.dataSourceProvider = dataSourceProvider;
    }

    @Override
    public boolean start() {
        try {
            Flyway flyway = new Flyway();
            flyway.setTable("db_version");
            flyway.setDataSource(this.dataSourceProvider.getDataSource());
            flyway.migrate();
            return true;
        } catch (Exception e) {
            logger.error("FlywayPlugin cannot start.", e);
            return false;
        }
    }

    @Override
    public boolean stop() {
        this.dataSourceProvider = null;
        return true;
    }

}
